/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：太平金科-基础组件封装层-SpringBoot组件封装-缺省实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taipingframework.boot.web.listeners;

import com.taipingframework.monitor.task.MonitorTask;
import com.taipingframework.utility.thread.threadfactory.SmartThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DefaultListener implements ServletContextListener {

    private ScheduledExecutorService taskExecutor;
    private MonitorTask task;

    public DefaultListener(Environment environment, MonitorTask monitorTask) {
        String threadPrefix = environment.getProperty("application.threadpool.threadPrefix", "zxb-listener");
        SmartThreadFactory threadFactory = new SmartThreadFactory(threadPrefix);
        this.taskExecutor = Executors.newScheduledThreadPool(1, threadFactory);
        this.task = monitorTask;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String[] stackTraceArray = Arrays.stream(Thread.currentThread().getStackTrace())
                .map(StackTraceElement::toString)
                .toArray(String[]::new);
        log.debug("DefaultListener.contextInitialized\r\n\r\tat {}", String.join("\r\n\r\tat ", stackTraceArray[1]));

        taskExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.MINUTES);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        String[] stackTraceArray = Arrays.stream(Thread.currentThread().getStackTrace())
                .map(StackTraceElement::toString)
                .toArray(String[]::new);
        log.debug("DefaultListener.contextDestroyed\r\n\r\tat {}", String.join("\r\n\r\tat ", stackTraceArray[1]));
        if (!task.hasStop()) {
            task.stopTask();
        }
        while (!task.hasTaskComplete()) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
                break;
            }
        }
        taskExecutor.shutdownNow();
    }

}
